package com.authine.cloudpivot.ext.controller.trainingData;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 *  “基层组织” 学习记录（二）
 **/
@RestController
@RequestMapping("/public/learngingRecord")
@Slf4j
public class LearningRecordController extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  “基层组织” 学习记录（二）  审批流完成后 数据写到-“基层组织” 学习记录二 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.LearningRecord, bizId);

        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("LearningRecordDetail");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人


        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            String learningRecordCode = (String) map.get("learningRecordCode");


            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.LearningRecordBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-基层组织 学习记录 二 操作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                log.info("基础表-基层组织 学习记录 二 操作失败  id={}",  learningRecordCode);
                log.info(e.getMessage(), e);
            }

        }
    }


    /**
     *  调用存储过程
     *  -----学习记录
     * exec   SyncLearnRecord
     *    FID       nvarchar(100),	   ----学习记录基础FID
     *    WorkDesc	   nvarchar(200)  ----工作说明
     * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.LearningRecordBase);
        StringBuilder sql = new StringBuilder("SELECT  learningRecordFid,workDesc from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程

        String learningRecordFid = MapUtils.getString(map,"learningRecordFid","");
        String workDesc = MapUtils.getString(map,"workDesc","");

        Assert.isFalse(StringUtils.isEmpty(learningRecordFid),"{}不能为空","learningRecordFid");
        Assert.isFalse(StringUtils.isEmpty(workDesc),"{}不能为空","workDesc");
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncLearnRecord '%s','%s'",
                learningRecordFid,workDesc );

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }


    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);

        String  manadeptFNumber = MapUtils.getString(bizObject.getData(),"manadeptFNumber","");
        String  comdeptFNumber = MapUtils.getString(bizObject.getData(),"comdeptFNumber","");
        String activiyCode = "Activity17";
        if (manadeptFNumber.equals(comdeptFNumber)) {
            activiyCode = "Activity13";
        }

        final String finalActivityCode = activiyCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(" ").append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map data){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.LearningRecordBase);
        Map<String,Object> learningRecord = (Map<String, Object>) data.get("learningRecordFid");
        String learningRecordFid = MapUtils.getString(learningRecord, "id", "");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where learningRecordFid='").append(learningRecordFid).append("' ;");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();


        //审批时间
        data.put("auditDate",map.get("auditDate"));
        //审批人
        data.put("auditer",map.get("auditer"));
        //基层组代码隐藏
        data.put("baseorgCode",map.get("baseorgCode"));
        //基层组织代码
        data.put("baseorgFID",map.get("baseorgFID"));
        //基层组织
        data.put("baseorgName",map.get("baseorgName"));
        //公司代码隐藏
        data.put("comcode",map.get("comcode"));
        //公司
        data.put("comcodeFID",map.get("comcodeFID"));
        //公司主责部门
        data.put("comdeptFName",map.get("comdeptFName"));
        //公司主责部门代码
        data.put("comdeptFNumber",map.get("comdeptFNumber"));
        //说明
        data.put("fDesc",map.get("fDesc"));
        //类型代码隐藏
        data.put("filetypeCode",map.get("filetypeCode"));
        //类型
        data.put("filetypeFID",map.get("filetypeFID"));
        //名称
        data.put("fName",map.get("fName"));
        //备注
        data.put("fNote",map.get("fNote"));
        //职能代码隐藏
        data.put("funcode",map.get("funcode"));
        //职能代码
        data.put("funfid",map.get("funfid"));
        //管理部门
        data.put("manadeptFName",map.get("manadeptFName"));
        //管理部门代码
        data.put("manadeptFNumber",map.get("manadeptFNumber"));
        //公司主责岗
        data.put("pos2FName",map.get("pos2FName"));
        //公司主责岗代码
        data.put("pos2FNumber",map.get("pos2FNumber"));
        //管理部门责任岗
        data.put("pos3FName",map.get("pos3FName"));
        //管理部门责任岗代码
        data.put("pos3FNumber",map.get("pos3FNumber"));
        //r001
        data.put("r001",map.get("r001"));
        //r002
        data.put("r002",map.get("r002"));
        //r003
        data.put("r003",map.get("r003"));
        //r004
        data.put("r004",map.get("r004"));
        //r005
        data.put("r005",map.get("r005"));
        //r006
        data.put("r006",map.get("r006"));
        //r007
        data.put("r007",map.get("r007"));
        //r008
        data.put("r008",map.get("r008"));
        //r009
        data.put("r009",map.get("r009"));
        //r010
        data.put("r010",map.get("r010"));
        //代码隐藏
        data.put("learningRecordCode",map.get("learningRecordCode"));
        //代码
        data.put("learningRecordFid",map.get("learningRecordFid"));
        //工作说明
        data.put("workDesc",map.get("workDesc"));

        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
}
